package 死锁;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class _01_循环打印 {

    private static final Object lock = new Object();

    private static int count = 0;

    private static int times = 10;

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < times; i++) {
                synchronized (lock) {
                    while (count % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("A");
                    count++;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < times; i++) {
                synchronized (lock) {
                    while (count % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("B");
                    count++;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < times; i++) {
                synchronized (lock) {
                    while (count % 3 != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("C");
                    count++;
                    lock.notifyAll();
                }
            }
        }).start();
    }
}
